<?php

namespace App\Http\Model;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class LuckDraw extends Base
{
    protected $luckDrawAwardLogTable = 'luck_draw_award_log';//抽奖活动奖品日志表
    protected $luckDrawAwardPoolTable = 'luck_draw_award_pool';//抽奖活动奖品池表
    protected $luckDrawLogTable = 'luck_draw_log';//抽奖活动日志表
    protected $luckDrawUserPropTable = 'luck_draw_user_prop';//抽奖活动用户道具表
    protected $luckDrawUserPropLogTable = 'luck_draw_user_prop_log';//抽奖道具日志表
    protected $luckDrawPoolsUserProp = 'wish_pools_user_prop';//恋爱卡
    protected $luckDrawPoolsUserPropLog = 'wish_pools_user_prop_log';//恋爱卡日志
    protected $wishPoolsUniverseValueLog = 'wish_pools_universe_change_log';//全服星辰值变动记录
    protected $financeWealthStreamTable = 'wish_pools_send_award_log';//发放奖励记录表

    protected $table = 'wish_pools_config';
    protected $luckBaseTable = 'luck_draw';//许愿池基本配置
    protected $wPoolTable = 'wish_pools_pool';
    protected $wPoolConfigTable = 'wish_pools_pool_config';
    protected $wOrderTable = 'wish_pools_order';
    protected $wDrawTable = 'wish_pools_draw';
    protected $wWhiteTable = 'wish_pools_white';
    protected $wStatisticsTable = 'wish_pools_statistics';
    protected $giftTable = 'gift_library';
    protected $wGiftTable = 'wish_pools_gift';//展示礼物表
    protected $wPoolUserTable = 'wish_pools_pool_user';//个人池用户
    protected $wPoolWhiteTable = 'wish_pools_pool_white';//许愿池奖池白名单

    //许愿池配置缓存
    protected $wishPoolConfigKey = 'UNIVERSE:CONFIG';//string UNIVERSE:CONFIG => {string}
    //许愿池奖池缓存
    protected $wishLuckPoolKey = 'UNIVERSE:POOL';//string UNIVERSE:POOL => {string}
    //许愿池奖池配置缓存
    protected $wishLuckPoolConfigKey = 'UNIVERSE:POOLCONFIG:';//string UNIVERSE:POOLCONFIG:{poolId} => {string}
    //许愿池奖池配置数据缓存
    public $wishLuckPoolDataKey = '{UNIVERSE:POOLDATA:%s:%s}'; //奖池 {UNIVERSE:POOLDATA:{$level }:{poolId}}
    //许愿池个人奖池
    public $wishLuckSelfPoolDataKey = '{UNIVERSE:USERPOOLDATA:%s:%s:%s}';//奖池 {UNIVERSE:USERPOOLDATA:{userId}:{$level}:{$poolId}}

    //用户抽奖数
    protected $userDrawNumKey = 'UNIVERSE:USERDRAW:NUM:';//string UNIVERSE:USERDRAW:NUM:{userId} => {num}
    //许愿池展示礼物缓存
    protected $wishPoolsGiftKey = 'UNIVERSE:GIFTCONFIG:';//string UNIVERSE:GIFTCONFIG:{pool_level} => {string}
    //许愿池用户每周抽奖次数缓存
    protected $userDrawNumWeekKey = 'UNIVERSE:USERDRAW:WEEKNUM:';//string UNIVERSE:USERDRAW:WEEKNUM:{ymd}:{userid} => {num}
    //许愿池用户每日抽奖数据统计缓存
    protected $userDrawNumDayKey = 'UNIVERSE:USERDRAW:DAYNUM:';//hash UNIVERSE:USERDRAW:DAYNUM:{ymd}:{userid} => {draw_no/prop_diamond_num/reward_diamond_num}
    protected $_redisKeyUserExpNum = 'LUCKDRAW:CACHE:USER:EXP:%d:%s';//使用过的告白币

    const USER_PROP_TYPE_EXCHANGE = 1000; //钻石兑换道具
    const USER_PROP_TYPE_DRAW = 2000;     //抽奖消耗
    const USER_PROP_TYPE_RECYCLE = 2001;     //回收消耗


    const USER_PROP_TYPE_DESC = [
        //抽奖页面用钻石兑换
        self::USER_PROP_TYPE_EXCHANGE => '钻石兑换',
        //抽奖页面抽奖消耗
        self::USER_PROP_TYPE_DRAW => '抽奖消耗',
        self::USER_PROP_TYPE_RECYCLE => '回收消耗',
    ];

    public  function getDescFromType($type){
        return self::USER_PROP_TYPE_DESC[$type]??'';
    }

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 抽奖活动详情
     */
    public function luckDrawInfo($luckId){
        $info = DB::table($this->luckBaseTable)->where('id', $luckId)->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
    * 许愿池中奖记录列表
    */
    public function awardListV2($page, $limit, $where){
        $query = DB::table($this->wDrawTable);
        $query = $query->where('reward_diamond_num', '>=', 5200);
        if(!empty($where['user_id'])) {
            $query = $query->where('user_id', $where['user_id']);
        }
        if(!empty($where['id'])) {
            $query = $query->where('id', '>', $where['id']);
        }
        if(!empty($where['created_at_st'])) {
            $query = $query->where('created_at', '>=', $where['created_at_st']);
        }
        $query = $query->selectRaw('sum(gift_num) as gift_num, order_id, gift_id, user_id, created_at,pool_level')
            ->groupBy('order_id', 'gift_id')
            ->orderBy('order_id', 'desc')
            ->offset($page * $limit)->limit($limit);
        $drawList = $query->get();
        $result = self::objToArray($drawList);

        return $result;
    }

    /**
     * 许愿池滚动列表最新倒叙
     */
    public function marquee($limit){
        $result = DB::table($this->wDrawTable)->orderBy('created_at',"DESC")->limit($limit)->get();
        $result = self::objToArray($result);

        return $result;
    }

    /**
     * 许愿池奖池奖品列表
     */
    public function awardPoolGiftList(){
        $list = DB::table($this->luckDrawAwardPoolTable)->where('status',1)->get();
        $list = self::objToArray($list);
        $result = [];
        if(!empty($list)) {
            foreach($list as $key=>$val) {
                $val['pool'] = json_decode($val['pool'], true);
                foreach($val['pool'] as $v2) {
                    $v2['pool_id'] = $val['id'];
                    $k2 = $val['id'].'-'.$v2['id'];

                    $result[$k2] = $v2;
                }
                $list[$key] = $val;
            }
        }

        return $result;
    }

    /**
     * 获取用户告白币数量
     */
    public function getLuckDrawUserProp($userId, $luckId){
        $info = DB::table($this->luckDrawUserPropTable)
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->first();
        $info = self::objToArray($info);


        return $info;
    }

    /**
     * 扣减用户告白币
     * @return bool
     */
    public function decrLuckDrawUserProp($userId, $luckId, $num){
        try {
            if(empty($userId) || empty($num)) {
                return false;
            }
            $num = abs($num);

            $res = DB::table($this->luckDrawUserPropTable)
                ->where('luck_id', $luckId)
                ->where('user_id', $userId)
                ->where('status', 1)
                ->where('deleted', 0)
                ->update([
                    'avail' =>DB::raw('`avail`-' . $num),
                    'used' =>DB::raw('`used`+' . $num),
                ]);
            if(empty($res)) {
                return false;
            }

            $log = [
                "luck_id" => $luckId,
                "user_id" => $userId,
                "change" => 0-$num,
                "type" => 2000,
                "desc" => '许愿池消耗',
            ];
            $logId = DB::table($this->luckDrawUserPropLogTable)->insertGetId($log);
            if(empty($logId)) {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * 许愿池奖池奖品列表
     */
    public function poolAwardList($luckId){
        $query = DB::table($this->luckDrawAwardPoolTable)->where('luck_id', $luckId);
        if($luckId == 1000) {
            $query = $query->where('id', 2008);
        }else{
            $query = $query->where('status', 1);
        }
        $list = $query->first();
        $list = self::objToArray($list);

        $result = [];
        if(!empty($list) && !empty($list['pool'])) {
            $list = json_decode($list['pool'], true);
            if(!empty($list)) {
                $result = $list;
            }
        }

        return $result;
    }

    /**
     * 许愿池奖池奖品列表
     */
    public function getLuckDrawPoolConfig($poolId){
        $list = DB::table($this->luckDrawAwardPoolTable)->where('id', $poolId)->first();
        $list = self::objToArray($list);

        if(!empty($list['pool'])) {
            $list['pool'] = json_decode($list['pool'], true);
        }

        return $list;
    }

    /**
     * 获取许愿奖池配置信息
     */
    public function getWishPoolConfig(){
        $key = $this->wishPoolConfigKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key,86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }


    public function updateGameRule($data)
    {
        $gameRule = $data['gameRule'];
        $res = DB::table($this->table)->where("id", "=", '1')->update(['rule' => $gameRule]);
        if ($res) {
            $key = $this->wishPoolConfigKey;
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if (!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }
    }

    public function getGameRule()
    {
        $key = $this->wishPoolConfigKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key,86400, json_encode($list));
            }
        }

        return $list;
    }



    /**
     * 获取个人池配置
     */
    public function getWishLuckPoolUserId($userId, $level){
        $info = DB::table($this->wPoolUserTable)
            ->where('user_id', $userId)
            ->where('pool_level', $level)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
     * 星辰变奖池信息
     */
    public function getWishLuckPool($luckId){
        $key = $this->wishLuckPoolKey.$luckId;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wPoolTable)->where('pool_level',$luckId)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        $list = array_column($list, null, 'id');

        return $list;
    }

    /**
     * 获取许愿池奖池配置
     */
    public function getWishLuckPoolConfig($poolId){
        $key = $this->wishLuckPoolConfigKey.$poolId;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wPoolConfigTable)->where('pool_id', $poolId)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    /**
     * 获取星辰变用户每周抽奖次数缓存
     */
    public function getUserWishLuckDrawNumByWeek($userId, $luckId){
        $startWeek = Carbon::today()->startOfWeek()->toDateString();
        $endWeek = Carbon::today()->endOfWeek()->toDateString();
        $cacheKey = $this->userDrawNumWeekKey.$luckId.'|'.$startWeek.'|'.$endWeek.':'.$userId;
        $num = Redis::get($cacheKey);
        if(empty($num)) {
            $query = DB::table($this->wOrderTable)
                ->where('created_at', '>=', $startWeek.' 00:00:00')
                ->where('created_at', '<=',  $endWeek.' 23:59:59')
                ->where('pool_level', $luckId)
                ->where('user_id', $userId);
            $num = $query->sum('num');
        }
        $num = (int) $num;

        Redis::set($cacheKey, $num);
        Redis::expire($cacheKey, 14*86400);

        return $num;
    }

    /**
     * 获取用户白名单
     */
    public function getWishLuckWhite($userId, $luckId){
        $list = DB::table($this->wWhiteTable)
            ->where('user_id', $userId)
            ->where('status', 0)
            ->where('pool_level', $luckId)
            ->where('is_delete', 0)
            ->get();
        $list = self::objToArray($list);

        return $list;
    }

    //新增星辰变订单记录
    public function addWishLuckOrder($data)
    {
        $id = DB::table($this->wOrderTable)->insertGetId($data);

        return $id;
    }

    //星辰变自指定奖池抽取
    public function drawWishLuckUser($level,$poolId, $userId)
    {
        $key = sprintf($this->wishLuckSelfPoolDataKey, $level ,$userId, $poolId);
        $poolConfigId = aliasIndex($key);

        return $poolConfigId;
    }

    //许愿转盘自指定奖池抽取
    public function drawWishLuck($level, $poolId)
    {
        $key = sprintf($this->wishLuckPoolDataKey, $level, $poolId);
        $poolConfigId = aliasIndex($key);

        return $poolConfigId;
    }

    //累加星辰变用户每周抽奖次数缓存
    public function incrUserDrawWeekNum($userId, $num, $luckId)
    {
        if($num <= 0) {
            return false;
        }
        $startWeek = Carbon::today()->startOfWeek()->toDateString();
        $endWeek = Carbon::today()->endOfWeek()->toDateString();
        $cacheKey = $this->userDrawNumWeekKey.$luckId.'|'.$startWeek.'|'.$endWeek.':'.$userId;
        $new = Redis::INCRBY($cacheKey, $num);

        return $new;
    }

    //新增许愿池抽奖记录
    public function addWishLuckDraw($data)
    {
        $id = DB::table($this->wDrawTable)->insertGetId($data);

        return $id;
    }

    //更新许愿池白名单
    public function updateWishLuckWhite($id, $orderId)
    {
        $res = DB::table($this->wWhiteTable)->where('id', $id)->update(['status'=>1, 'order_id'=>$orderId]);

        return $res;
    }

    //更新星辰变订单记录
    public function updateWishLuckDraw($orderId, $rewardDiamondNum)
    {
        $res = DB::table($this->wOrderTable)->where('id', $orderId)->update(['reward_diamond_num'=>$rewardDiamondNum]);

        return $res;
    }

    //更新许愿池个人池用户记录
    public function updateWishLuckUserPoolLog($id, $propDiamondNum, $rewardDiamondNum, $drawNum)
    {
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('prop_diamond_num', $propDiamondNum);
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('reward_diamond_num', $rewardDiamondNum);
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('draw_num', $drawNum);

        return $res;
    }

    //更新许愿池用户每日抽奖数据统计缓存
    public function updateWishLuckUserDay($luckId, $userId, $propDiamondNum, $rewardDiamondNum, $drawNum)
    {
        $now = time();
        $ymd = date("Ymd", $now);
        $cacheKey = $this->userDrawNumDayKey.$luckId.':'.$ymd.':'.$userId;
        Redis::HINCRBY($cacheKey, 'prop_num', $drawNum);
        Redis::HINCRBY($cacheKey, 'prop_diamond_num', $propDiamondNum);
        Redis::HINCRBY($cacheKey, 'reward_diamond_num', $rewardDiamondNum);

        return 1;
    }

    //个人池用户自动处理移入移出
    public function handleWishLuckUserPool($userId, $poolUser, $luckId)
    {
        $now = time();
        $ymd = date("Ymd", $now);
        do {
            //判断
            if(empty($poolUser)) {
                //自动移入
                //用户近7天转盘总累计 产出-消耗 产出/消耗
                $info = DB::table($this->wOrderTable)
                    ->where('user_id', $userId)
                    ->where('created_at', '>=', date('Y-m-d H:i:s', ($now - 2*86400)))
                    ->selectRaw('sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num')
                    ->first();
                $info = objToArray($info);
                $info['prop_diamond_num'] = empty($info['prop_diamond_num']) ? 0 : $info['prop_diamond_num'];//消耗
                $info['reward_diamond_num'] = empty($info['reward_diamond_num']) ? 0 : $info['reward_diamond_num'];//产出
                //盈亏
                $info['profit_loss'] = $info['reward_diamond_num'] - $info['prop_diamond_num'];
                //返奖率%
                $info['profit_rate'] = empty($info['prop_diamond_num']) ? 0 : round(($info['reward_diamond_num']*100)/$info['prop_diamond_num'], 2);

                //获取当前默认个人亏损池
                $config = DB::table($this->wPoolTable)->where('status', 1)->where('pool_type', 2)->where('if_default', 1)->first();
                $config = objToArray($config);
                if(!empty($config)) {
                    $in_profit_loss = empty($config['in_profit_loss']) ? 0 : $config['in_profit_loss'];//进入个人池盈亏
                    $in_profit_rate = empty($config['in_profit_rate']) ? 0 : $config['in_profit_rate'];//进入个人池返奖率%
                    $info['in_profit_loss'] = $in_profit_loss;
                    $info['in_profit_rate'] = $in_profit_rate;
                    //判断
                    if(!empty($in_profit_loss) || !empty($in_profit_rate)) {
                        $flag1 = $flag2 = 0;
                        //盈亏
                        if($in_profit_loss!=0 && $info['profit_loss']>=$in_profit_loss) {
                            $flag1 = 1;
                        }
                        //返奖率%
                        if($in_profit_rate!=0 && $info['profit_rate']>=$in_profit_rate) {
                            $flag2 = 1;
                        }

                        $flag = 0;
                        if(!empty($in_profit_loss) && !empty($in_profit_rate) && $flag1==1 && $flag2==1) {
                            $flag = 1;
                        }elseif(!empty($in_profit_loss) && empty($in_profit_rate) && $flag1==1){
                            $flag = 1;
                        }elseif(empty($in_profit_loss) && !empty($in_profit_rate) && $flag2==1){
                            $flag = 1;
                        }
                        $info['flag'] = $flag;
                        $info['flag1'] = $flag1;
                        $info['flag2'] = $flag2;

                        if($flag == 1) {
                            //移除钻石数
                            $outDiamondNum = intval($info['profit_loss']*$config['out_profit_rate']*0.01*-1);
                            $info['outDiamondNum'] = $outDiamondNum;
                            //初始化许愿池个人奖池配置数据缓存指定用户
                            $poolConfigMap = $this->getWishLuckPoolConfig($config['id']);
                            if(empty($poolConfigMap)) {
                                break;
                            }
                            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
                            $this->makeWishWheelSelfPoolDataByPoolIdUserId($config['id'], $userId, $poolConfigMap);
                            //新增许愿池个人池用户
                            $poolUserId = $this->addWishLuckPoolUser($userId, 0, $config['id'], $outDiamondNum);
                            $info['poolUserId'] = $poolUserId;

                            break;
                        }
                    }
                }

                //获取当前默认个人盈利池
                $config = DB::table($this->wPoolTable)->where('status', 1)->where('pool_type', 3)->where('if_default', 1)->first();
                $config = objToArray($config);
                if(!empty($config)) {
                    $in_profit_loss = empty($config['in_profit_loss']) ? 0 : $config['in_profit_loss'];//进入个人池盈亏
                    $in_profit_rate = empty($config['in_profit_rate']) ? 0 : $config['in_profit_rate'];//进入个人池返奖率%
                    $info['in_profit_loss'] = $in_profit_loss;
                    $info['in_profit_rate'] = $in_profit_rate;
                    //判断
                    if(!empty($in_profit_loss) || !empty($in_profit_rate)) {
                        $flag1 = $flag2 = 0;
                        //盈亏
                        if($in_profit_loss!=0 && $info['profit_loss']<=$in_profit_loss) {
                            $flag1 = 1;
                        }
                        //返奖率%
                        if($in_profit_rate!=0 && $info['profit_rate']<=$in_profit_rate) {
                            $flag2 = 1;
                        }

                        $flag = 0;
                        if(!empty($in_profit_loss) && !empty($in_profit_rate) && $flag1==1 && $flag2==1) {
                            $flag = 1;
                        }elseif(!empty($in_profit_loss) && empty($in_profit_rate) && $flag1==1){
                            $flag = 1;
                        }elseif(empty($in_profit_loss) && !empty($in_profit_rate) && $flag2==1){
                            $flag = 1;
                        }
                        $info['flag'] = $flag;
                        $info['flag1'] = $flag1;
                        $info['flag2'] = $flag2;

                        if($flag == 1) {
                            //移除钻石数
                            $outDiamondNum = intval($info['profit_loss']*$config['out_profit_rate']*0.01*-1);
                            $info['outDiamondNum'] = $outDiamondNum;
                            //初始化许愿转盘个人奖池配置数据缓存指定用户
                            $poolConfigMap = $this->getWishLuckPoolConfig($config['id']);
                            if(empty($poolConfigMap)) {
                                break;
                            }
                            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
                            $this->makeWishWheelSelfPoolDataByPoolIdUserId($config['id'], $userId, $poolConfigMap);
                            //新增许愿转盘个人池用户
                            $poolUserId = $this->addWishLuckPoolUser($userId, 0, $config['id'], $outDiamondNum);
                            $info['poolUserId'] = $poolUserId;

                            break;
                        }
                    }
                }

            }else{
                //自动移出
                //用户个人池记录
                $info = $this->getWishLuckPoolUserById($poolUser['id']);
                if(empty($info)) {
                    break;
                }
                //不移除
                if(empty($info['out_diamond_num'])) {
                    break;
                }
                //移除钻石数
                $out_diamond_num = empty($info['out_diamond_num']) ? 0 : $info['out_diamond_num'];
                //盈亏
                $info['profit_loss'] = $info['reward_diamond_num'] - $info['prop_diamond_num'];
                //获取奖池配置
                $config = DB::table($this->wPoolTable)->where('id', $poolUser['pool_id'])->first();
                $config = objToArray($config);

                //亏损池
                if($config['pool_type'] == 2) {
                    if($info['profit_loss'] <= $out_diamond_num) {
                        $this->wishWheelDelPoolUser($info['id'], $info['user_id'], 0);
                        $info['亏损池'] = '移除';
                    }
                    break;
                }

                //盈利池
                if($config['pool_type'] == 3) {
                    if($info['profit_loss'] >= $out_diamond_num) {
                        $this->wishWheelDelPoolUser($info['id'], $info['user_id'], 0);
                        $info['盈利池'] = '移除';
                    }
                    break;
                }
            }
        } while (false);

    }

    /**
     * 初始化许愿池个人奖池配置数据缓存指定用户
     */
    public function makeWishWheelSelfPoolDataByPoolIdUserId($poolId, $userId, $data){
        $key = sprintf($this->wishLuckSelfPoolDataKey, $userId, $poolId);
        aliasInit($key, $data);
        return true;
    }

    //新增许愿池个人池用户
    public function addWishLuckPoolUser($userId, $adminId, $poolId, $outDiamondNum)
    {
        $data = [];
        $data['user_id'] = $userId;
        $data['add_time'] = date('Y-m-d H:i:s', time());
        $data['admin_id'] = $adminId;
        $data['pool_id'] = (int) $poolId;
        $data['out_diamond_num'] = (int) $outDiamondNum;

        $id = DB::table($this->wPoolUserTable)->insertGetId($data);

        return $id;
    }

    //获取许愿池个人池根据ID
    public function getWishLuckPoolUserById($id)
    {
        $info = DB::table($this->wPoolUserTable)
            ->where('id', $id)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //许愿池删除个人池用户
    public function wishLuckDelPoolUser($id, $userId, $adminId)
    {
        $update = [];
        $update['deladmin_id'] = $adminId;
        $update['del_time'] = date('Y-m-d H:i:s', time());
        $update['is_delete'] = 1;

        $res = DB::table($this->wPoolUserTable)->where('id', $id)->update($update);
        if($res) {
            $keys = Redis::Keys('{UNIVERSE:USERPOOLDATA:'.$userId.':*');
            foreach ($keys as $key) {
                Redis::expire($key, 86400*60);
            }
        }

        return $res;
    }

    /**
     * 许愿池订单中奖记录列表
     */
    public function orderAwardList($orderId){
        $info = DB::table($this->wOrderTable)->where('id', $orderId)->first();
        $info = self::objToArray($info);
        if(empty($info)) {
            return [];
        }

        $drawList = DB::table($this->wDrawTable)
            ->where('order_id', $orderId)
            ->selectRaw('sum(gift_num) as gift_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, gift_id, pool_level')
            ->groupBy('gift_id')
            ->get();
        $drawList = self::objToArray($drawList);
        if(empty($drawList)) {
            return [];
        }
        $info['drawList'] = $drawList;

        return $info;
    }

    /**
     * 获取使用过的告白币
     */
    public function getUsed($userId, $luckId){
        $week = date('Y-m-d', strtotime('this week'));
        $key = sprintf($this->_redisKeyUserExpNum, $luckId, $week);
        return intval(Redis::HGET($key, $userId)??0);
    }

    /**
     * 获取用户中奖记录
     */
    public function wishLuckAllAwardList($page, $limit, $where){
        $drawList = DB::table($this->wDrawTable)
            ->where('user_id', $where['user_id'])
            ->orderBy('id','DESC')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        $result = self::objToArray($drawList);

        return $result;
    }


    //编辑许愿池配置
    public function editWishLuckConfig($params)
    {
        $upData = [];
        if(!empty($params['need_num'])) {
            $upData['need_num'] = $params['need_num'];
        }
        if(isset($params['new_num'])) {
            $upData['new_num'] = $params['new_num'];
        }
        if(!empty($params['draw_num_1'])) {
            $upData['draw_num_1'] = $params['draw_num_1'];
        }
        if(!empty($params['draw_num_2'])) {
            $upData['draw_num_2'] = $params['draw_num_2'];
        }
        if(!empty($params['draw_img_1a'])) {
            $upData['draw_img_1a'] = $params['draw_img_1a'];
        }
        if(!empty($params['draw_img_1b'])) {
            $upData['draw_img_1b'] = $params['draw_img_1b'];
        }
        if(!empty($params['draw_img_2a'])) {
            $upData['draw_img_2a'] = $params['draw_img_2a'];
        }
        if(!empty($params['draw_img_2b'])) {
            $upData['draw_img_2b'] = $params['draw_img_2b'];
        }
        if(isset($params['full_rate'])) {
            $upData['full_rate'] = $params['full_rate'];
        }
        if(isset($params['in_profit_loss'])) {
            $upData['in_profit_loss'] = $params['in_profit_loss'];
        }
        if(isset($params['in_profit_rate'])) {
            $upData['in_profit_rate'] = $params['in_profit_rate'];
        }
        if(isset($params['out_profit_loss'])) {
            $upData['out_profit_loss'] = $params['out_profit_loss'];
        }
        if(isset($params['out_profit_rate'])) {
            $upData['out_profit_rate'] = $params['out_profit_rate'];
        }
        if(isset($params['changePoolLimit']) && !empty($params['changePoolLimit'])) {
            $upData['changePoolLimit'] = $params['changePoolLimit'];
        }
        if(isset($params['costPoolNum']) && !empty($params['costPoolNum'])) {
            $upData['costPoolNum'] = $params['costPoolNum'];
        }
        if(isset($params['openMinutes']) && !empty($params['openMinutes'])){
            $upData['openMinutes'] = $params['openMinutes'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->table)->update($upData);

        $cacheKey = $this->wishPoolConfigKey;
        Redis::del($cacheKey);

        return $res;
    }

    /**
     * 获取许愿池信息根据ID
     */
    public function getWishLuckPoolById($poolId){
        $info = DB::table($this->wPoolTable)->where('id', $poolId)->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
     * 初始化许愿池个人奖池配置数据缓存
     */
    public function makeWishLuckSelfPoolData($level, $poolId, $data){
        //查询个人池用户列表
        $list = DB::table($this->wPoolUserTable)->where('is_delete',0)->where('pool_id', $poolId)->where('pool_level',$level)->get();
        $list = self::objToArray($list);
        if(empty($list)){
            return false;
        }
        foreach($list as $v){
            $key = sprintf($this->wishLuckSelfPoolDataKey, $v['user_id'], $level ,$poolId);
            aliasInit($key, $data);
        }
        return true;
    }

    /**
     * 初始化许愿池配置数据缓存
     */
    public function makeWishLuckPoolData($level, $poolId, $data){
        $key = sprintf($this->wishLuckPoolDataKey, $level ,$poolId);
        aliasInit($key, $data);
    }

    //编辑许愿池
    public function editWishLuckPool($id, $params)
    {
        $upData = [];
        if(!empty($params['status'])) {
            $upData['status'] = $params['status'];
        }
        if(!empty($params['pool_name'])) {
            $upData['pool_name'] = $params['pool_name'];
        }
        if(!empty($params['min_num'])) {
            $upData['min_num'] = $params['min_num'];
        }
        if(!empty($params['max_num'])) {
            $upData['max_num'] = $params['max_num'];
        }
        if(!empty($params['if_default'])) {
            $upData['if_default'] = $params['if_default'];
        }
        if(isset($params['in_profit_loss'])) {
            $upData['in_profit_loss'] = $params['in_profit_loss'];
        }
        if(isset($params['in_profit_rate'])) {
            $upData['in_profit_rate'] = $params['in_profit_rate'];
        }
        if(isset($params['out_profit_rate'])) {
            $upData['out_profit_rate'] = $params['out_profit_rate'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->wPoolTable)->where('id', $id)->update($upData);

        $cacheKey = $this->wishLuckPoolKey.'1000';
        $cacheKey2 = $this->wishLuckPoolKey.'1001';
        Redis::del($cacheKey);
        Redis::del($cacheKey2);

        return $res;
    }

    //编辑许愿池奖池配置
    public function editWishLuckPoolConfig($poolId, $id, $giftId, $giftNum)
    {
        $upData = [];
        $upData['gift_id'] = $giftId;
        $upData['gift_num'] = $giftNum;

        $res = DB::table($this->wPoolConfigTable)->where('id', $id)->update($upData);

        $cacheKey = $this->wishLuckPoolConfigKey.$poolId;
        Redis::del($cacheKey);

        return $res;
    }

    /**
     * 获取许愿池奖池根据奖池类型
     */
    public function getWishLuckPoolByDefault($poolType, $poolLevel){
        $info = DB::table($this->wPoolTable)->where('pool_type', $poolType)->where('if_default', 1)->where('pool_level', $poolLevel)->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增许愿池奖池
    public function addWishLuckPool($poolName, $minNum, $maxNum, $poolType, $ifDefault, $poolLevel)
    {
        $data = [];
        $data['pool_name'] = $poolName;
        $data['min_num'] = $minNum;
        $data['max_num'] = $maxNum;
        $data['pool_type'] = $poolType;
        $data['if_default'] = $ifDefault;
        $data['status'] = 2;
        $data['pool_level'] = $poolLevel;

        $id = DB::table($this->wPoolTable)->insertGetId($data);

        $cacheKey = $this->wishLuckPoolKey.'1000';
        $cacheKey2 = $this->wishLuckPoolKey.'1001';
        Redis::del($cacheKey);
        Redis::del($cacheKey2);
        return $id;
    }

    //新增许愿池奖池配置
    public function addWishLuckPoolConfig($poolId, $itemNo)
    {
        $data = [];
        $data['pool_id'] = $poolId;
        $data['item_no'] = $itemNo;

        $id = DB::table($this->wPoolConfigTable)->insertGetId($data);

        return $id;
    }

    /**
     * 许愿池奖池配置剩余数量
     */
    public function getWishLuckPoolData($poolId, $level){
        $result = [];
        $key = sprintf($this->wishLuckPoolDataKey,$level , $poolId);
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        if(!empty($valKey)) {
            if(Redis::EXISTS($valKey)) {
                $list = Redis::LRANGE($valKey, 0, -1);
                if(!empty($list)) {
                    foreach($list as $val) {
                        if(empty($result[$val])) {
                            $result[$val]['id'] = $val;
                            $result[$val]['num'] = 0;
                        }
                        $result[$val]['num'] = $result[$val]['num'] + 1;
                    }
                }
            }
        }
        $result = array_values($result);

        return $result;
    }

    //新增许愿池白名单
    public function addWishLuckWhite($level, $userId, $giftId, $adminId, $poolId=0)
    {
        $data = [];
        $data['user_id'] = $userId;
        $data['gift_id'] = $giftId;
        $data['admin_id'] = $adminId;
        $data['pool_id'] = $poolId;
        $data['status'] = 0;
        $data['pool_level'] = $level;

        $id = DB::table($this->wWhiteTable)->insertGetId($data);

        return $id;
    }

    //删除许愿池白名单
    public function delWishLuckWhite($whiteId)
    {
        $id = DB::table($this->wWhiteTable)->where('id', $whiteId)->where('is_delete', 0)->update(['is_delete'=>1]);

        return $id;
    }

    //取消投放许愿池白名单
    public function cancelWishLuckWhite($whiteId)
    {
        $id = DB::table($this->wWhiteTable)->where('id', $whiteId)->where('status', 0)->update(['status'=>1]);

        return $id;
    }

    //新增许愿池展示礼物
    public function wishLuckAddGift($poolLevel, $giftId, $sort)
    {
        $data = [];
        $data['gift_id'] = $giftId;
        $data['sort'] = $sort;
        $data['is_delete'] = 0;
        $data['pool_level'] = $poolLevel;

        $id = DB::table($this->wGiftTable)->insertGetId($data);

        $cacheKey = $this->wishPoolsGiftKey.'1000';
        $cacheKey2 = $this->wishPoolsGiftKey.'1001';
        Redis::del($cacheKey);
        Redis::del($cacheKey2);

        return $id;
    }

    //许愿池删除展示礼物
    public function wishLuckDelGift($id)
    {
        $id = DB::table($this->wGiftTable)->where('id', $id)->update(['is_delete'=>1]);

        $cacheKey = $this->wishPoolsGiftKey.'1000';
        $cacheKey2 = $this->wishPoolsGiftKey.'1001';
        Redis::del($cacheKey);
        Redis::del($cacheKey2);

        return $id;
    }

    /**
     * 获取许愿池展示礼物
     */
    public function getWishLuckGift($luckId){
        $key = $this->wishPoolsGiftKey.$luckId;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wGiftTable)->where('is_delete', 0)->orderBy('sort', 'asc')->where('pool_level',$luckId)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    //获取许愿池个人池用户
    public function getWishLuckPoolUser($userId)
    {
        $info = DB::table($this->wPoolUserTable)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //查看个人奖池剩余数量
    public function getWishLuckSelfPoolData($poolId, $userId){
        $result = [];
        $key = sprintf($this->wishLuckSelfPoolDataKey, $userId, $poolId);
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        if(!empty($valKey)) {
            if(Redis::EXISTS($valKey)) {
                $list = Redis::LRANGE($valKey, 0, -1);
                if(!empty($list)) {
                    foreach($list as $val) {
                        if(empty($result[$val])) {
                            $result[$val]['id'] = $val;
                            $result[$val]['num'] = 0;
                        }
                        $result[$val]['num'] = $result[$val]['num'] + 1;
                    }
                }
            }
        }
        $result = array_values($result);

        return $result;
    }

    //许愿池自指定奖池中抽取指定的余量
    public function drawWishLuckAppoint($pool_level, $poolId, $poolConfigId, $userId=0)
    {
        if(empty($userId)) {
            $key = sprintf($this->wishLuckPoolDataKey, $pool_level ,$poolId);
        }else{
            $key = sprintf($this->wishLuckSelfPoolDataKey, $userId, $poolId);
        }
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        //移除指定参数
        $res = Redis::LREM($valKey, 1, $poolConfigId);
        if($res) {
            //加入另一个池子
            $key_0 = $key.':ALIAS:0';
            $key_1 = $key.':ALIAS:1';
            if($valKey === $key_0) {
                Redis::lpush($key_1, $poolConfigId);
            }else{
                Redis::lpush($key_0, $poolConfigId);
            }
        }
        return $res;
    }

    //统计许愿池数据
    public function wishPoolStatistics($dateSt, $dateEt, $poolLevel)
    {
        $info = DB::table($this->wOrderTable)
            ->where('created_at', '>=', $dateSt)
            ->where('created_at', '<=', $dateEt)
            ->where('pool_level', $poolLevel)
            ->selectRaw('count(DISTINCT user_id) as user_num, sum(num) as draw_num, sum(prop_num) as prop_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num,pool_level')
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增许愿池每日统计
    public function addWishPoolStatistics($data)
    {
        $id = DB::table($this->wStatisticsTable)->insertGetId($data);

        return $id;
    }

    //获取许愿池爆出记录
    public function getDrawList($orderId){
        $list = DB::table($this->wDrawTable)
                ->select(DB::raw('sum(gift_num) as gift_num, gift_id,pool_level'))
                ->where('order_id',$orderId)
                ->groupBy('gift_id')
                ->get();
        $list = self::objToArray($list);
        return $list;
    }

    //增加用户恋爱卡
    public function addTiket(int $luckId, int $userId, int $num){
        $exist = DB::table($this->luckDrawPoolsUserProp)
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->exists();

        //如果存在
        if ($exist) {
            $count = DB::table($this->luckDrawPoolsUserProp)
                ->where('luck_id', $luckId)
                ->where('user_id', $userId)
                ->where('status', 1)
                ->where('deleted', 0)
                ->increment("avail", $num);
            return $count > 0;
        }

        //如果不存在
        $insert = [
            'luck_id' => $luckId,
            'user_id' => $userId,
            'avail' => $num,
            'used' => 0,
            'status' => 1,
            'deleted' => 0
        ];
        $status = DB::table($this->luckDrawPoolsUserProp)->insert($insert);
        return $status;
    }

    //记录购买恋爱卡日志
    public function addTiketLog(int $luckId, int $userId, int $type, int $change){
        if (empty($luckId) || empty($userId) || empty($type)) {
            return false;
        }
        $insert = [
            'luck_id' => $luckId,
            'user_id' => $userId,
            'type' => $type,
            'change' => $change,
            'desc' => $this->getDescFromType($type)
        ];
        $status = DB::table($this->luckDrawPoolsUserPropLog)->insert($insert);
        return $status;
    }

    //获取可用恋爱卡
    public function getAvail(int $luckId, int $userId){
        $userPropModel = DB::table($this->luckDrawPoolsUserProp)
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->first();
        return (int)$userPropModel->avail;
    }

    /**
     * 扣减用户恋爱卡
     * @return bool
     */
    public function decrUniverseTickerUserProp($userId, $luckId, $num){
        try {
            if(empty($userId) || empty($num)) {
                return false;
            }
            $num = abs($num);

            $res = DB::table($this->luckDrawPoolsUserProp)
                ->where('luck_id', $luckId)
                ->where('user_id', $userId)
                ->where('status', 1)
                ->where('deleted', 0)
                ->update([
                    'avail' =>DB::raw('`avail`-' . $num),
                    'used' =>DB::raw('`used`+' . $num),
                ]);
            if(empty($res)) {
                return false;
            }

            $log = [
                "luck_id" => $luckId,
                "user_id" => $userId,
                "change" => 0-$num,
                "type" => 2000,
                "desc" => '宇宙星辰变消耗',
            ];
            $logId = DB::table($this->luckDrawPoolsUserPropLog)->insertGetId($log);
            if(empty($logId)) {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }

    //记录星辰值
    public function insertStarValueLog($data){
        $status = DB::table($this->wishPoolsUniverseValueLog)->insert($data);
        return $status;
    }

    //获取用户总计星辰值
    public function getStarValueByUser($userId){
        $value = DB::table($this->wishPoolsUniverseValueLog)->where('user_id',$userId)->sum('add_star_value');
        return $value;
    }

    //发放奖励日志
    public function insertSendAwardLog($data){
        $status = DB::table($this->financeWealthStreamTable)->insert($data);
        return $status;
    }

}
